
//
//  XHF_AFN.m
//  haojia
//
//  Created by 徐宏飞 on 16/4/15.
//  Copyright © 2016年 徐宏飞. All rights reserved.
//

#import "XHF_AFN.h"
#import <AFNetworking.h>

@implementation XHF_AFN


+ (void)geturlStr:(NSString *)urlStr Block:(AppToolBlock)block
{
    // 网址转码 处理中文字符 AFN可以自己执行,暂时用不上
    //    NSString *str = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:NSUTF8StringEncoding];
    
    
    // 编码
    NSString *urlEncode = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];


    AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    //    // 缓存部分
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    //    NSLog(@"AAAA%@", path);
    //    // 生成路径
    NSString *pathLast = [NSString stringWithFormat:@"/%lu.plist",(unsigned long)[urlStr hash]];
    //    NSLog(@"QQQQ%@", pathLast);
    NSString *PathName = [path stringByAppendingString:pathLast];
    
    
    
    
    
    [manager GET:urlEncode parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [responseObject writeToFile:PathName atomically:YES];
        //        NSLog(@"缓存---------- %@", PathName);
        if (responseObject) {
            //            NSLog(@"%@", responseObject);
            block(responseObject);
        }else{
            NSLog(@"返回数据为空请检查");
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败==== %@",error);
        // 请求失败执行从本地取出数据
        if ([[NSFileManager defaultManager] fileExistsAtPath:PathName]) {
            id result = [NSMutableDictionary dictionaryWithContentsOfFile:PathName];
            // 通过block回调数据
            //            NSLog(@"AQQQ%@", result);
            block(result);
        }
        
    }];
}

//// post请求
//+ (void)getPostWithURL:(NSString *)url Body:(NSString *)body Block:(AppToolBlock)block
//{
//    
//    
//    // post地址
//    NSString *strEncode = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//    NSURL *urlStr = [NSURL URLWithString:strEncode];
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlStr];
//    
//    // 设置请求对象的请求方式为POST请求,默认是get请求
//    [request setHTTPMethod:@"POST"];
//    // 将body体转化成data型数据
//    NSData *bodyData = [body dataUsingEncoding:NSUTF8StringEncoding];
//    // 设置为请求的body体
//    [request setHTTPBody:bodyData];
//    
//    // 创建一个专门配置session的类,是系统对session兑现的一个标准配置
//    NSURLSessionConfiguration *sessionConfigu = [NSURLSessionConfiguration defaultSessionConfiguration];
//    
//    //    // 缓存部分
//    //    NSString *pathX = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
//    //    // 生成路径
//    //    NSString *pathLastX = [NSString stringWithFormat:@"/Caches/ShyNing/%lu.plist", (unsigned long)[url hash]];
//    //    NSString *pathNameX = [pathX stringByAppendingString:pathLastX];
//    //    NSLog(@"缓存---------- %@", pathLastX);
//    //stringByAppendingPathComponent
//    
//    // 缓存部分
//    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//    // 生成路径
//    NSString *pathLastV = [NSString stringWithFormat:@"%lu.plist", (unsigned long)[urlStr hash]];
//    NSString *filePath = [document stringByAppendingPathComponent:pathLastV];
//    
//    //    NSLog( @"^^^^^^^^^^^^^^^%@", filePath);
//    
//    // 另一个初始化方法
//    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfigu];
//    NSURLSessionDataTask *postTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        if (data) {
//            
//            id resultX = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//            // 请求成功后执行
//            // responseObject返回数据位NSData
//            [resultX writeToFile:filePath atomically:YES];
//            
//            block(resultX);
//        }else{
//            NSLog(@"失败==== %@",error);
//            // 请求失败执行从本地取出数据
//            if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
//                id result = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
//                // 通过block回调数据
//                block(result);
//            }
//            
//        }
//        
//        
//        
//        
//        
//    }];
//    [postTask resume];
//}
//

+ (void)postHTTPWithURL:(NSString *)url params:(NSDictionary *)params success:(void (^)(NSDictionary *success))success failure:(void (^)(NSError *error))failure {
    
    AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];

    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.securityPolicy.allowInvalidCertificates = YES;
    
    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success) {
            id resultX = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            success(resultX);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failure) {
            
            failure(error);
        }
    }];
}


@end
